#include "configfilereader.h"
#include <QJsonDocument>
#include <QJsonParseError>
#include <QJsonObject>
#include <QFile>
#include <QMessageBox>
#include <globalControl.h>
#include <QRegularExpression>
#include <QRegularExpressionMatch>


#if QT_VERSION >= 0x060000
#include <QStringConverter>
#endif

#ifdef DEBUG_MODE
#include <QDebug>
#endif

ConfigFileReader::ConfigFileReader(QObject *parent)
    : QObject(parent)
{
}

void ConfigFileReader::readOrder(QString filePath)
{
    pTabList = new QList<TAB>;

    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        QMessageBox::warning(NULL, u8"警告", u8"Json配置文件打开失败！", QMessageBox::Ok);
        file.close();
        return;
    }
#ifdef DEBUG_MODE
    qDebug() << "Json配置文件打开成功";
#endif

    QByteArray data = file.readAll();
    file.seek(0);
    file.close();

    QTextStream in(&data);

#if QT_VERSION >= 0x060000
    // Qt 6.x 相关代码
    in.setEncoding(QStringConverter::Utf8);
#else
    // Qt 5.x 或更早版本相关代码
    in.setCodec("UTF-8");
#endif


    int level = 0;

    QPair<QString, QStringList> pair;
    QStringList list;

    static QRegularExpression re(R"(\"([^\"]*)\")");

    while(!in.atEnd()){
        QString str = in.readLine();
        QString value;
        QRegularExpressionMatch match = re.match(str);
        if(match.hasMatch()) {
            value = match.captured(1);
            switch(level){
            case 1:
                pair.first = value;
                break;
            case 2:
                list.append(value);
                break;
            default:
                break;
            }
        }
        if(str.contains("{")){
            ++level;
        }
        if(str.contains("}")){
            --level;
            switch(level){
            case 1:
                pair.second = list;
                orderStack.push_back(pair);
                break;
            case 2:
                list.append(value);
                break;
            default:
                break;
            }
            list.clear();
            pair.first = "";
        }
    }
}

void ConfigFileReader::read(QString filePath)
{
    this->filePath = filePath;

    readOrder(filePath);

    pTabList = new QList<TAB>;



    QFile file(filePath);
    if (!file.open(QIODevice::ReadOnly)) {
        QMessageBox::warning(NULL, u8"警告", u8"Json配置文件打开失败！", QMessageBox::Ok);
        file.close();
        return;
    }

    // readOrder(filePath);

#ifdef DEBUG_MODE
    qDebug() << "Json配置文件打开成功";
#endif

    QTextStream in(&file);

#if QT_VERSION >= 0x060000
    // Qt 6.x 相关代码
    in.setEncoding(QStringConverter::Utf8);

#else
    // Qt 5.x 或更早版本相关代码
    in.setCodec("UTF-8");
#endif

    QString data = in.readAll();

    file.close();

    QJsonDocument doc = QJsonDocument::fromJson(data.toUtf8());

    if (!doc.isObject()) {
        return;
    }
#ifdef DEBUG_MODE
    qDebug() << "Json文件格式检查通过";
#endif


    QJsonObject obj = doc.object();

    for (auto const &each : std::as_const(orderStack)) {
        TAB tab;
        tab.name = each.first;

        QJsonObject subObj = obj[tab.name].toObject();
        QStringList subKeys = each.second;

        for(auto const &subKey : std::as_const(subKeys)){
            CONFIGOBJECT cfgObj;
            cfgObj.name = subKey;

            cfgObj.path = subObj[subKey].toString();
            tab.list.push_back(cfgObj);
        }

        pTabList->push_back(tab);
    }

}

QList<TAB> *ConfigFileReader::getTabList()
{
    return pTabList;
}


void ConfigFileReader::write()
{
    QFile file(filePath);
    if (file.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
        file.close();
    }
    if (!file.open(QIODevice::ReadWrite)) {
        QMessageBox::warning(NULL, u8"警告", u8"Json配置文件打开失败或该文件不存在！", QMessageBox::Ok);
        file.close();
        return;
    }

#ifdef DEBUG_MODE
    qDebug() << "Json配置文件打开成功";
#endif

    QTextStream ts(&file);

#if QT_VERSION >= 0x060000
    // Qt 6.x 相关代码
    ts.setEncoding(QStringConverter::Utf8);

#else
    // Qt 5.x 或更早版本相关代码
    ts.setCodec("UTF-8");
#endif


    file.seek(0);

    ts << "{\n";

    int index = 0;
    // for(auto const &obj : std::as_const(orderStack)){
    //     ts << "\t\"" + QString::fromLocal8Bit(obj.first.toLocal8Bit()) + "\" : {\n";
    //     int subIndex = 0;
    //     for(auto const &subObj : std::as_const(obj.second)){
    //         ts << "\t\t\"";
    //         ts << QString::fromLocal8Bit(subObj.toLocal8Bit());
    //         ts << "\" : \"";
    //         ts << pTabList->at(index).list.at(subIndex).path.toUtf8();
    //         if(subIndex == obj.second.length() - 1) ts << "\"\n";
    //         else ts << "\",\n";
    //         ++subIndex;
    //     }
    //     if(index == orderStack.length() - 1) ts << "\t}\n";
    //     else ts << "\t},\n";
    //     index++;
    // }
    for(auto const &obj : std::as_const(*pTabList)){
        ts << "\t\"" + QString::fromLocal8Bit(obj.name.toLocal8Bit()) + "\" : {\n";
        int subIndex = 0;
        for(auto const &subObj : std::as_const(obj.list)){
            ts << "\t\t\"";
            ts << QString::fromLocal8Bit(subObj.name.toLocal8Bit());
            ts << "\" : \"";
            ts << subObj.path.toUtf8();
            if(subIndex == obj.list.length() - 1) ts << "\"\n";
            else ts << "\",\n";
            ++subIndex;
        }
        if(index == pTabList->length() - 1) ts << "\t}\n";
        else ts << "\t},\n";
        index++;
    }
    ts << "}";

    file.close();
}
